// plugin/components/zhmap/zhmap.js
import {getScenicArea, getScenicAreaDetail, getRoadDetail} from "./request.js";
import {closePoiPopup} from '../zhgeo/zhgeo.dom'
import {defaultRootScenicId, ZhgeoIcons} from "./zhconfig"
import {getServeUrl} from '../../index'


Component({
    /**
     * 组件的属性列表
     */
    properties: {
        rootScenicId: String 
    },

    /**
     * 组件的初始数据
     */
    data: {
        /// poi half screen
        poiHalfScreenShow: false, 
        /// ScenicAreaChildren
        scenicTypeList: [],
        /// poi详情half screen
        isAudioPlay: false,
        poiDetailHalfScreenShow: false,
        poiOfPoiDetail: null,
        audioRemainingTime: "00:00",
        loadingAudio: true,
        zhgeoIcons: new ZhgeoIcons(),
        roadMultiArray: [[],[]],
        roadMultiIndex: [0, 0],
        showRoadControl: false,
        multimap: [],
        baseUrl: getServeUrl(),
        scenicShowControl: false,
        scenicShowHalfScreenShow: false,
        scenicShowList: [],
        targetShowTimeScenic: null,
    },

    /**
     * 组件的方法列表
     */
    methods: {
        /// poi选择 half screen
        openPoiHalfScreen() {
            this.setData({
                poiHalfScreenShow: true
            })
        },
        /// 显示表演时间
        openScenicShowHalfScreen() {
            let that = this;
            let scenic_list = []    // 所有包含表演时间的景点
            let children_scenic_area_type = that.scenicArea.children_scenic_area_type
            for (let t=0; t<children_scenic_area_type.length; ++t) {
                for (let s=0; s<children_scenic_area_type[t].items.length; ++s) {
                    let item = children_scenic_area_type[t].items[s]
                    if (item.nearest_show_time != null) {
                        scenic_list.push(item)
                    }
                }
            }
            if (scenic_list.length > 0) {
                // 排序
                scenic_list.sort(function(a, b) {
                    return a.nearest_show_time.getTime() - b.nearest_show_time.getTime()
                })
            }
    
            this.setData({
                scenicShowHalfScreenShow: true,
                scenicShowList: scenic_list
            })
        },
    
        showTargetScenicShowTimeList(evt) {
            let that = this;
            let scenicid = evt.currentTarget.dataset.scenicid
            let children_scenic_area_type = that.scenicArea.children_scenic_area_type
            let scenic = null
            for (let t=0; scenic == null &&t<children_scenic_area_type.length; ++t) {
                for (let s=0; s<children_scenic_area_type[t].items.length; ++s) {                
                    let item = children_scenic_area_type[t].items[s]
                    if (item.id == scenicid) {
                        scenic = item
                        break;
                    }
                }
            }
            if (scenic == null || scenic.today_show_time == null) {
                return
            }
    
            var recentDate = null
            if (scenic.recent_show_time != null) {
                for (const i in scenic.recent_show_time) {
                    if (recentDate == null) {
                        recentDate = scenic.recent_show_time[i]
                    } else {
                        if (recentDate.getTime() > scenic.recent_show_time[i].getTime()) {
                            recentDate = scenic.recent_show_time[i]
                        }
                    }
                }
            }
            let showTimeList = []
            for (const i in scenic.today_show_time) {
                for (let m=0; m<scenic.today_show_time[i].length; ++m) {
                    let ttm = scenic.today_show_time[i][m]
                    if (recentDate != null) {
                        if (recentDate.getTime() - 1000 <= ttm.getTime()) {
                            showTimeList.push(ttm)
                        }
                    } else {
                        showTimeList.push(ttm)
                    }
                }
            }
            showTimeList.sort(function(a, b) {
                return a.getTime() - b.getTime()
            })
            scenic.show_time_str_list = []
            for (let i=0; i<showTimeList.length; ++i) {
                let st = showTimeList[i]
                let ss = st.getMonth() + '月' + st.getDate() + '日'
                    + ' ' +  st.getHours() + '时' + st.getMinutes() + '分'
                scenic.show_time_str_list.push(ss)
            }
            that.setData({
                targetShowTimeScenic: scenic
            })
        },
    
        showAllScenicShowTimeList() {
            var that = this
            that.setData({
                targetShowTimeScenic: null
            })
        },
    
        _showTypeCheckboxChange(e, typeList) {
            const values = e.detail.value;
            for (let i=0; i<typeList.length; ++i) {
                let show = false;
                for (let j=0; j<values.length; ++j) {
                    if (typeList[i].id == values[j]) {
                        show = true;
                        if (!typeList[i].show) {
                            typeList[i].show = true;
                            this.scenicArea.showPois(typeList[i]);
                        }
                        break;
                    }
                }
                if (!show) {
                    if (typeList[i].show) {
                        typeList[i].show = false;
                        this.scenicArea.hidePois(typeList[i]);
                    }
                }
            }
        },
    
        scenicTypeCheckboxChange(e) {
            this._showTypeCheckboxChange(e, this.data.scenicTypeList);
        },
    
        showPoiDetailHalfScreen(poi) {
            var that = this;
            if (that.audioContext != null) {
                that.audioContext.stop();
                that.audioContext.destroy();
                that.audioContext = null;
            }
            if (poi.show_audio) {
                that.audioContext = wx.createInnerAudioContext();
                that.audioContext.onCanplay(function() {
                    console.log("can play")
                    if (that.data.loadingAudio) {
                        // that.audioContext.play();
                        // that.audioContext.pause();
                        // that.audioContext.seek(0);
                    }
                    // let tm = that.calcAudioTime();
                    that.setData({
                        loadingAudio: false,
                        // audioRemainingTime: tm
                    })
                })
                that.audioContext.onTimeUpdate(function() {
                    let tm = that.calcAudioTime();
                    that.setData({
                        audioRemainingTime: tm
                    });
                });
                that.audioContext.onEnded(function() {
                    that.setData({ isAudioPlay: false });
                })
            }
            if (poi.detailLoaded) {
                if (that.audioContext != null) {
                    that.audioContext.src = poi.audio_file;
                }
                that.setData({
                    loadingAudio: true,
                    isAudioPlay: false,
                    poiDetailHalfScreenShow: true,
                    poiOfPoiDetail: poi,
                    audioRemainingTime: "00:00",
                });
            } else {
                getScenicAreaDetail(poi, function(p) {
                    that.showPoiDetailHalfScreen(p);
                });
            }
        },
        closeDetailHalfScreen() {
            var that = this;
            let poi = that.data.poiOfPoiDetail;
            closePoiPopup(poi);
        },
        //播放
        playAudio: function () {
            var that = this;
            if (that.data.loadingAudio) return;
            that.audioContext.play();
            setTimeout(() => {
                let status = that.audioContext.paused;
              }, 100)
            this.setData({ isAudioPlay: true });
        },
        // 停止
        stopAudio: function () {
            var that = this;
            that.audioContext.pause();
            this.setData({ isAudioPlay: false });
        },
        routerNavToChildScenic: function() {
            let that = this;
            if (that.data.poiOfPoiDetail == null) {
                return;
            }
            this.triggerEvent('changeScenic', {
                scenicId: this.data.poiOfPoiDetail.id
            })
        },
        routerNavToMultimap: function(e) {
            var scenicId = e.currentTarget.dataset.scenicid
            this.triggerEvent('redirectScenic', {
                scenicId: scenicId
            })  
        },
        navigateToPoi: function () {
            let that = this;
            if (that.data.poiOfPoiDetail == null || that.data.poiOfPoiDetail.location == null) {
                return;
            }
            const pnt = [that.data.poiOfPoiDetail.location.longitude, that.data.poiOfPoiDetail.location.latitude]; //wgs84ToGcj02(that.data.poiOfPoiDetail.location.longitude, that.data.poiOfPoiDetail.location.latitude)
            const latitude = pnt[1]
            const longitude = pnt[0]
            wx.openLocation({
                latitude,
                longitude,
                scale: that.data.poiOfPoiDetail.zoom
              })
    
        },
        showLocation: function() {
            let that = global.wx;
            that.scenicArea.showLocation();
        },
        triggerTrail: function() {
    
        },
        bindRoudMultiPickerChange(e) {
        //   console.log('picker发送选择改变，携带值为', e.detail.value)
          let that = this;
          if (that.scenicArea.roadShowing != null) {
            that.scenicArea.hideRoad(that.scenicArea.roadShowing)
          }
          if (e.detail.value[0] > 0) {
            let iType = e.detail.value[0] - 1;
            let road = that.scenicArea.road_type_list[iType].roads[e.detail.value[1]]
          //   console.log(road)
            if (road.detailLoaded) {
              that.scenicArea.showRoad(road)
            } else {
              getRoadDetail(that.scenicArea, road, function(roadDetail) {
                that.scenicArea.showRoad(roadDetail)
              })
            }          
          }
          this.setData({
            roadMultiIndex: e.detail.value
          })
        },
        bindRoudMultiPickerColumnChange(e) {
          let that = this;
        //   console.log('修改的列为', e.detail.column, '，值为', e.detail.value);
          var data = {
            roadMultiArray: this.data.roadMultiArray,
            roadMultiIndex: this.data.roadMultiIndex
          };
          data.roadMultiIndex[e.detail.column] = e.detail.value;
          switch (e.detail.column) {
            case 0:
              data.roadMultiArray[1] = [];
              if (e.detail.value > 0) {
                let iType = e.detail.value - 1;
                for (let m=0; m<that.scenicArea.road_type_list[iType].roads.length; ++m) {
                    data.roadMultiArray[1].push(that.scenicArea.road_type_list[iType].roads[m].name);
                }
                data.roadMultiIndex[1] = 0;
                console.log(data.roadMultiIndex);
              }
              break;
          }
          console.log(data.roadMultiIndex);
          this.setData(data);
        },
        calcAudioTime: function() {
            let that = this
            const thisRemaingTime = Math.round(that.audioContext.duration - that.audioContext.currentTime);
            if (thisRemaingTime != that.audioRemainingTime) {
                that.audioRemainingTime = thisRemaingTime;
                const mm = Math.floor(thisRemaingTime / 60 )
                const ss = Math.round(thisRemaingTime - mm * 60);
                return mm + ':' + ss;
            } else {                
                const mm = Math.floor(that.audioRemainingTime / 60 )
                const ss = Math.round(that.audioRemainingTime - mm * 60);
                return mm + ':' + ss;
            }
        }

    },
    lifetimes: {
        ready: function() {
            var that = this
            const container = this.selectComponent('#zhmap-container')
            getScenicArea(that.data.rootScenicId, function(d) { 
                that.scenicArea = d; 
                that.triggerEvent('updateBarTitle', {
                    scenicName: that.scenicArea.name
                })
                that.scenicArea.createMap(that, container, function() {
                    that.scenicArea.initTileLayer(); 
                    that.scenicArea.showAreaContour();
                    that.scenicArea.initPois(); 
    
                    let _roadMultiArray = [['无'],[]];
                    for (let i=0; i<that.scenicArea.road_type_list.length; ++i) {
                      _roadMultiArray[0].push(that.scenicArea.road_type_list[i].name);
                    //   if (i == 0) {
                    //     for (let m=0; m<that.scenicArea.road_type_list[i].roads.length; ++m) {
                    //       _roadMultiArray[1].push(that.scenicArea.road_type_list[i].roads[m].name);
                    //     }
                    //   }
                    }    
                    container.setData({
                        compassRotateAngle: that.scenicArea.compassRotateAngle ?? 0,
                    })
                    that.setData({
                        rootScenicId: that.scenicArea.id,
                        scenicTypeList: that.scenicArea.children_scenic_area_type,
                        roadMultiArray: _roadMultiArray,
                        showRoadControl: that.scenicArea.road_type_list.length > 0,
                        multimap: that.scenicArea.multimap ?? [],
                        markerBorderColor: that.scenicArea.cma_color,
                    })
                }); 
            }, true);
        },
        detached: function () {
            var that = this;
            if (that.audioContext != null) {
                that.audioContext.stop();
                that.audioContext.destroy();
                that.audioContext = null;
            }
            if (that.scenicArea.cron_task_mng != null) {
                that.scenicArea.cron_task_mng.stop();
                that.scenicArea.cron_task_mng = null;
            }
        }
    },
    pageLifetimes: {
      show: function() {
        console.log('show page')
        var that = this;
        if (that.scenicArea != null && that.scenicArea.cron_task_mng != null 
              && !that.scenicArea.cron_task_mng.running) {
            that.scenicArea.cron_task_mng.start();
        }
      },
      hide: function() {
        console.log('hide page')
        var that = this;
        if (that.scenicArea != null && that.scenicArea.cron_task_mng != null
              && that.scenicArea.cron_task_mng.running) {
            that.scenicArea.cron_task_mng.stop();
        }
      },
    }
})
